package com.example.aopdemo;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class OrderServiceAspect {

    // 定义切入点表达式
    @Pointcut("execution(* com.example.aopdemo.OrderService.*(..))")
    public void orderServiceMethods() {}

    // 1. 前置增强
    @Before("orderServiceMethods()")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 后置增强（仅对add和delete方法）
    @After("execution(* com.example.aopdemo.OrderService.add(..)) || " +
            "execution(* com.example.aopdemo.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 返回通知，获取方法返回值
    @AfterReturning(pointcut = "orderServiceMethods()", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        System.out.println("方法 " + joinPoint.getSignature().getName() +
                " 的返回值: " + result);
    }

    // 4. 环绕通知，计算方法执行时间
    @Around("orderServiceMethods()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        // 执行目标方法
        Object result = proceedingJoinPoint.proceed();

        long end = System.currentTimeMillis();
        System.out.println("方法 " + proceedingJoinPoint.getSignature().getName() +
                " 执行时间: " + (end - start) + "ms");

        return result;
    }
}